package com.example.softwareconfigurationcoursedesign;

import javax.swing.*;
import java.io.File;
import java.util.Iterator;
import java.util.List;

public class LogService {
    public LogService() {
    }

    public static void addLogs(User user, String logContext) {
        LogDaoimpl logdaoimpl = new LogDaoimpl();
        Logs log = new Logs(user.getPhoneNumber(), user.getPhoneNumber(), user.getPhoneNumber(), user.getPhoneNumber(),user.getPhoneNumber());
        log.setUserId(user.getPhoneNumber());
        log.setTimes(DateUtil.getDateTimeNow());
        log.setLogContext(logContext);
        logdaoimpl.addLog(log);
    }

    public static void queryLogs(User user) {
        LogDaoimpl logdaoimpl = new LogDaoimpl();
        final List<Logs> logsList = logdaoimpl.queryLog(user.getPhoneNumber());
        Iterator<Logs> list = logsList.iterator();

        System.out.println("该账号的日志记录如下:");
        System.out.println("账号            用户名            登录方法                 时间                操作");

        String logInfo = null;
        for (Logs log : logsList) {
            logInfo += log.getUserId() + "   " + log.getTimes() + "  " + log.getLogContext() + "\n";
        }

        System.out.println(logInfo);

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择保存路径");
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int userSelection = fileChooser.showSaveDialog(null);
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File saveDirectory = fileChooser.getSelectedFile();
            String savePath = saveDirectory.getAbsolutePath() + "/poi.xls";

            try {
//                PoiExpExcel.poiExp(logsList, savePath);
                System.out.println("Excel文件已保存成功");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("保存Excel文件时出错");
            }
        }
    }
}
